package com.ckf.login_wx.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
















import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ckf.login_wx.entity.Bill;
import com.ckf.login_wx.entity.Material;
import com.ckf.login_wx.entity.Odd;
import com.ckf.login_wx.entity.Repertory;
import com.ckf.login_wx.entity.Sell;
import com.ckf.login_wx.entity.Xinsell;
import com.ckf.login_wx.servic.BillService;
import com.ckf.login_wx.servic.OddService;
import com.ckf.login_wx.servic.SellService;
import com.ckf.login_wx.servic.XinsellService;
import com.ckf.login_wx.util.Getpo;
import com.ckf.login_wx.util.Idname;
import com.github.pagehelper.PageHelper;

@RestController
@RequestMapping("/Sp")
public class SpBillcontroller {
	@Autowired
    private BillService billService;
	@Autowired
    private XinsellService XinsellService;
	@Autowired
    private OddService OddService;
    @PostMapping("/addordincome")
    public Map<String, Object> addordincome(String source,String time,String remark,String money) throws ParseException{
        Map<String, Object> map = new HashMap<>();
        Bill bill=new Bill();
        bill.setMoney(Double.parseDouble(money));
        bill.setSource(source);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        bill.setTime(simpleDateFormat.parse(time));
        bill.setRemark(remark);
        bill.setStatus(1);
		if (billService.save(bill)){
            map.put("code",200);
            map.put("result","添加成功");
            System.out.println("添加成功");
        }else {
        	map.put("code",200);
            map.put("result","no");
        }
        return map;
    }
    @GetMapping("/incomelistall")
    public Object incomelistall(HttpServletRequest request){
    	String pageNo=request.getParameter("page");
		String pagesize=request.getParameter("limit");
    	Integer i = Integer.parseInt(pageNo); 
    	Integer n = Integer.parseInt(pagesize);
        Map<String, Object> map = new HashMap<>();
    	List<Bill> a= billService.list(new QueryWrapper<Bill>().eq("status", 1));
    	map.put("code",0);
        map.put("count",a.size());
        map.put("msg"," ");
    	if(n!=5000)PageHelper.offsetPage((i-1)*n, n);
        map.put("data",billService.list(new QueryWrapper<Bill>().eq("status", 1)));
    return map;
    }
    @RequestMapping("/selebillbyid")
    public Object selebillbyid(String id){
    	Integer idint = Integer.parseInt(id);
        return billService.getById(idint);
    }
    @PostMapping("/upbillbyid")
    public Object upbillbyid(String id,String source,String time,String remark,String money) throws ParseException{
    	Map<String, Object> map = new HashMap<>();
        Integer i = Integer.parseInt(id);
        Bill bill=new Bill();
        bill.setId(i);
        bill.setMoney(Double.parseDouble(money));
        bill.setSource(source);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        bill.setTime(simpleDateFormat.parse(time));
        bill.setRemark(remark);
		if (billService.updateById(bill)){
            map.put("code",200);
            map.put("result","修改成功");
            System.out.println("修改成功");
        }else {
        	map.put("code",200);
            map.put("result","no");
        }
        return map;
    }
//    @GetMapping("/selebillid")
//    public Object selebillid(){
//    	List<String> odd=new ArrayList<String>();
//    	for(int n=0;n<sellService.list().size();n++){
//    		if(sellService.list().get(n).getOdd()!=null&&!sellService.list().get(n).getOdd().equals("")){
//        		odd.add(sellService.list().get(n).getOdd());
//    		}
//    	}
//    	HashSet<String> set=new LinkedHashSet<>(odd);
//    	for(String word:odd){
//    	    set.add(word);
//    	}
//        return set;
//    }
//    @GetMapping("/selebillid")
//    public Object selebillid(){
//    	List<String> odd=new ArrayList<String>();
//    	for(int n=0;n<billService.list().size();n++){
//    		if(billService.list().get(n).getOdd()!=null&&!billService.list().get(n).getOdd().equals("")){
//        		odd.add(billService.list().get(n).getOdd());
//    		}
//    	}
//    	HashSet<String> set=new LinkedHashSet<>(odd);
//    	for(String word:odd){
//    	    set.add(word);
//    	}
//        return set;
//    }
    @GetMapping("/selebillbyoddall")
    public Object selebillbyoddall(String talk){
    	QueryWrapper<Bill> queryWrapper0 = new QueryWrapper<>();
        Map<String, Object> mapuser0 = new HashMap<>();
    	if(talk.equals("")||talk==null){
            mapuser0.put("source","货款");
            queryWrapper0.allEq(mapuser0);
            return billService.list(queryWrapper0);
        }
    	QueryWrapper<Bill> queryWrapper = new QueryWrapper<>();
        Map<String, Object> mapuser = new HashMap<>();
        	mapuser.put("odd",talk);
        queryWrapper.allEq(mapuser);
        return billService.list(queryWrapper);
    }
    @GetMapping("/selebillbyodd")
    public Object selebillbyodd(String pagenew,String talk){
    	Integer i = Integer.parseInt(pagenew);
    	QueryWrapper<Bill> queryWrapper0 = new QueryWrapper<>();
        Map<String, Object> mapuser0 = new HashMap<>();
    	if(talk.equals("")||talk==null){
            mapuser0.put("source","货款");
            queryWrapper0.allEq(mapuser0);
       	 	PageHelper.offsetPage((i-1)*5, 5);
            return billService.list(queryWrapper0);
        }
    	QueryWrapper<Bill> queryWrapper = new QueryWrapper<>();
        Map<String, Object> mapuser = new HashMap<>();
        	mapuser.put("odd",talk);
        queryWrapper.allEq(mapuser);
    	//System.out.println(billService.list().size()+"***");
   	 	PageHelper.offsetPage((i-1)*5, 5);
        return billService.list(queryWrapper);
    }
    @PostMapping("/addbill")
    public Object addbill(int id,String debt,String time,String odd,String total,String source,String money,String saisie,String faf) throws ParseException{
    	if(Double.parseDouble(money)>Double.parseDouble(debt))return "实收金额大于应还金额";
    	String stu="";
    	Odd oddentity=OddService.list(new QueryWrapper<Odd>().eq("odd", odd)).get(0);
        Bill bill=new Bill();
        bill.setOdd(odd);
        bill.setMoney(Double.parseDouble(money));
        bill.setTotal(Double.parseDouble(total));
        bill.setDebt(Double.parseDouble(debt));
        bill.setSource(source);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        bill.setTime(simpleDateFormat.parse(time));
        bill.setRemark(odd);
        bill.setSaisie(saisie);
        bill.setAnq(oddentity.getAnq());
        bill.setPhone(oddentity.getPhone());
        bill.setName(oddentity.getName2());
        bill.setStatus(1);
		if(faf.equals("add")){
	        if (billService.save(bill)){
	        	oddentity.setDebt(oddentity.getDebt()-Double.parseDouble(money));
	        	OddService.updateById(oddentity);
	        	stu="添加成功";
	        }else {
	        	stu="添加失败";
	        }
		}
		if(faf.equals("up")){
			bill.setId(id);
	        if (billService.updateById(bill)){
	        	stu="修改成功";
	        }else {
	        	stu="修改失败";
	        }
		}
        return stu;
    }

    @PostMapping("/addbillbyphone")
    public Object addbillbyphone(String debt2,String time2,String phone,String source,String money2,String saisie2) throws ParseException{
    	if(Double.parseDouble(money2)>Double.parseDouble(debt2))return "实收金额大于应还金额";
    	List<Odd> list=OddService.list(new QueryWrapper<Odd>().eq("phone", phone).eq("status", 1));

    	String stu="";double moneysum=Double.parseDouble(money2);
    	for (int i = 0; i < list.size(); i++) {
        	Odd oddentity=list.get(i);
    		if(list.get(i).getDebt()==0)continue;//已经还完的货单跳过
    		Bill bill=new Bill();
    		if(moneysum>list.get(i).getDebt()||moneysum==list.get(i).getDebt()){
    			System.out.println("moneysum>list.get(i).getDebt()");
                bill.setMoney(list.get(i).getDebt());
                moneysum=moneysum-list.get(i).getDebt();
            	oddentity.setDebt(0.00);
            	
            	bill.setOdd(list.get(i).getOdd()+"");
                bill.setTotal(list.get(i).getTotal());
                bill.setDebt(list.get(i).getTotal());
                bill.setSource(source);
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                bill.setTime(simpleDateFormat.parse(time2));
                bill.setRemark("程序按电话还款");
                bill.setSaisie(saisie2);
                bill.setAnq(list.get(i).getAnq());
                bill.setName(list.get(i).getName2());
                bill.setPhone(list.get(i).getPhone());
                bill.setStatus(1);
                if (billService.save(bill)){
                	OddService.updateById(oddentity);
                	stu="添加成功";
                }else {
                	stu="添加失败";
                } 
    		}else{
    			System.out.println("moneysum<list.get(i).getDebt()");
                bill.setMoney(moneysum);
            	oddentity.setDebt(oddentity.getDebt()-moneysum);
            	
            	bill.setOdd(list.get(i).getOdd()+"");
                bill.setTotal(list.get(i).getTotal());
                bill.setDebt(list.get(i).getTotal());
                bill.setSource(source);
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                bill.setTime(simpleDateFormat.parse(time2));
                bill.setRemark("程序按电话还款");
                bill.setSaisie(saisie2);
                bill.setAnq(list.get(i).getAnq());
                bill.setName(list.get(i).getName2());
                bill.setPhone(list.get(i).getPhone());
                bill.setStatus(1);
                if (billService.save(bill)){
                	OddService.updateById(oddentity);
                	stu="添加成功";
                }else {
                	stu="添加失败";
                } 
                break;
    		}
		}
        return stu;
    }
    @PostMapping("/addincome")
    public Object addincome(int id,String time,String source,String money,String remark,String faf) throws ParseException{
    	String stu="";
        Bill bill=new Bill();
    	if(source.equals("投资")){
    		bill.setOdd("TZ");
    	}
        bill.setMoney(Double.parseDouble(money));
        bill.setSource(source);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        bill.setTime(simpleDateFormat.parse(time));
        bill.setRemark(remark);
        bill.setStatus(1);
		if(faf.equals("add")){
	        if (billService.save(bill)){
	        	stu="添加成功";
	        }else {
	        	stu="添加失败";
	        }
		}
		if(faf.equals("up")){
			bill.setId(id);
	        if (billService.updateById(bill)){
	        	stu="修改成功";
	        }else {
	        	stu="修改失败";
	        }
		}
        return stu;
    }
    @GetMapping("/delebillbyodd")
    public Object delebillbyodd(Integer id,String pagenew,String talk){
    	billService.removeById(id);
    	QueryWrapper<Bill> queryWrapper = new QueryWrapper<>();
        Map<String, Object> mapuser = new HashMap<>();
        mapuser.put("odd",talk);
        queryWrapper.allEq(mapuser);
    	Integer i = Integer.parseInt(pagenew);
    	System.out.println(billService.list(queryWrapper).size()+"***");
   	 	PageHelper.offsetPage((i-1)*5, 5);
        return billService.list(queryWrapper);
    }
    @GetMapping("/seleoddbymoneyall")
    public Object seleoddbymoneyall(){
    	double money=0;
    	Map<String, Object> map = new HashMap<>();
    	for(int n=0;n<billService.list().size();n++){
    		if(billService.list().get(n).getSource().equals("货款"))
    		money=money+billService.list().get(n).getMoney();
    	}
        map.put("money",money);
    	
        return map;
    }
  //按单号查询应还
    @RequestMapping("/seleoddbytotal")
    public Object seleoddbytotal(String odd){
    	List<Odd> list =OddService.list(new QueryWrapper<Odd>().eq("odd", odd));
    	List<Bill> listbill =billService.list(new QueryWrapper<Bill>().eq("odd", odd));
    	int money=0;
    	if(listbill.size()!=0)
    	for (int i = 0; i < listbill.size(); i++) {
			money+=listbill.get(i).getMoney();
		}
    	Map<String, Object> map = new HashMap<>();
        map.put("total",list.get(0).getTotal());
        map.put("money",list.get(0).getTotal()-money);
        
        return map;
    }
  //按电话查询应还
    @RequestMapping("/selephonebytotal")
    public Object selephonebytotal(String phone){
    	List<Odd> list =OddService.list(new QueryWrapper<Odd>().eq("phone", phone).eq("status", 1));
    	int money=0;
    	for (int i = 0; i < list.size(); i++) {
			money+=list.get(i).getDebt();
		}
    	Map<String, Object> map = new HashMap<>();
        //map.put("total",list.get(0).getTotal());
        map.put("money",money);
        
        return map;
    }
    @RequestMapping("/delebillbyid")
	public Object delebillbyid(Integer id){
    	if(billService.getById(id).getSource().equals("货款")){
    		return "货款不可删除";
    	}
		if(billService.removeById(id)){
			return "成功";	
		}else
			return "失败";	
	}
    @RequestMapping("/delebillall")
    public Object delebillall(String[] id){
    	
    	for (int i = 0; i < id.length; i++) {
    		try {
    			if(id[i].equals(""))continue;
    	    	int idint = Integer.parseInt(id[i]+"");
    	    	billService.removeById(idint);
			} catch (Exception e) {
				System.out.println("***********************************异常*************************************");
				return "异常";
			}
		}
		return "删除成功";
    }
	//货款管理table的billinfo
    @RequestMapping("/billinfo")
    public Object billinfo(HttpServletRequest request,String odd){
    	String pageNo=request.getParameter("page");
		String pagesize=request.getParameter("limit");
    	Integer i = Integer.parseInt(pageNo); 
    	Integer n = Integer.parseInt(pagesize);
        Map<String, Object> map = new HashMap<>();
    	List<Bill> a= billService.list((QueryWrapper<Bill>)Getpo.one("odd", odd));
    	map.put("code",0);
        map.put("count",a.size());
        map.put("msg"," ");
    	if(n!=5000)PageHelper.offsetPage((i-1)*n, n);
        map.put("data",billService.list((QueryWrapper<Bill>)Getpo.one("odd", odd)));
    return map;
    }
  //货款管理table的oddinfo
    @RequestMapping("/oddinfo")
    public Object oddinfo(HttpServletRequest request,String odd){
    	String pageNo=request.getParameter("page");
		String pagesize=request.getParameter("limit");
    	Integer i = Integer.parseInt(pageNo); 
    	Integer n = Integer.parseInt(pagesize);
        Map<String, Object> map = new HashMap<>();
    	List<Odd> a= OddService.list((QueryWrapper<Odd>)Getpo.one("odd", odd));
    	map.put("code",0);
        map.put("count",a.size());
        map.put("msg"," ");
    	if(n!=5000)PageHelper.offsetPage((i-1)*n, n);
        map.put("data",OddService.list((QueryWrapper<Odd>)Getpo.one("odd", odd)));
    return map;
    }
    @RequestMapping("/selebillbysearch")
    public Object selebillbysearch(HttpServletRequest request,String source,String odd,String remark,String anq,String phone,String time){
    	String pageNo=request.getParameter("page");
		String pagesize=request.getParameter("limit");
    	Integer i = Integer.parseInt(pageNo); 
    	Integer n = Integer.parseInt(pagesize); 
    	
    	QueryWrapper<Bill> queryWrapper = new QueryWrapper<>();
        if(time!=null&&!time.equals("")&&time.length()>13&&time.indexOf("-")!=-1){
            String timestart=time.substring(0,10);
            String timeend=time.substring(12);
            queryWrapper.le("time", timeend);
            queryWrapper.ge("time", timestart);
        }
        if(source.equals("投资")){
        	queryWrapper.like("remark", remark).like("source", source).like("status", 1);	
        }else if(source.equals("")){
        	if(phone.equals("")&&anq.equals("")){
        		queryWrapper.like("remark", remark).like("odd", odd).like("status", 1);
        	}else
        	queryWrapper.like("remark", remark).like("phone", phone).like("anq", anq).like("odd", odd).like("status", 1);
        }else
        queryWrapper.like("remark", remark).like("source", source).like("phone", phone).like("anq", anq).like("odd", odd).like("status", 1);
    	
        Map<String, Object> map = new HashMap<>();
    	List<Bill> a= billService.list(queryWrapper);
    	map.put("code",0);
        map.put("count",a.size());
        map.put("msg"," ");
    	if(n!=5000)PageHelper.offsetPage((i-1)*n, n);
        map.put("data",billService.list(queryWrapper));
        return map;
    }
    @RequestMapping("/billtotal")
    public Object billtotal(HttpServletRequest request){
    	int totalHk=0,totalTz=0,debt=0,total=0;
        Map<String, Object> map = new HashMap<>();
    	List<Bill> billlist= billService.list(new QueryWrapper<Bill>().eq("status", 1));
    	for (int i = 0; i < billlist.size(); i++) {
    		if(billlist.get(i).getSource().equals("货款"))
    			totalHk+=billlist.get(i).getMoney();
    		if(billlist.get(i).getSource().equals("投资"))
        		totalTz+=billlist.get(i).getMoney();
    		total+=billlist.get(i).getMoney();
		}
        map.put("totalHk",totalHk);
        map.put("total",total);
        map.put("totalTz",totalTz);
        //欠款统计部分
        HttpSession session= request.getSession();
        String username = session.getAttribute("username")+"";
        String quxian = session.getAttribute("quxian")+"";
        String truename = session.getAttribute("truename")+"";
        List<Odd> oddlist =OddService.list();
	    	if(quxian.equals("2")){
	    		System.out.println("进入角色："+truename);
	    		oddlist= OddService.list(new QueryWrapper<Odd>().eq("saisie", truename));
	    	}
        //List<Odd> oddlist= OddService.list();
    	for (int i = 0; i < oddlist.size(); i++) {
    		debt+=oddlist.get(i).getDebt();
		}
        map.put("debt",debt);
        return map;
    }
    @RequestMapping("/billtotalInfo")
    public Object billtotalInfo(String source,String odd,String remark,String anq,String phone,String time){
    	
    	
    	QueryWrapper<Bill> queryWrapper = new QueryWrapper<>();
        if(time!=null&&!time.equals("")&&time.length()>13&&time.indexOf("-")!=-1){
            String timestart=time.substring(0,10);
            String timeend=time.substring(12);
            queryWrapper.le("time", timeend);
            queryWrapper.ge("time", timestart);
        }
        if(source.equals("投资")){
        	queryWrapper.like("remark", remark).like("source", source).like("status", 1);	
        }else if(source.equals("")){
        	if(phone.equals("")&&anq.equals("")){
        		queryWrapper.like("remark", remark).like("odd", odd).like("status", 1);
        	}else
        	queryWrapper.like("remark", remark).like("phone", phone).like("anq", anq).like("odd", odd).like("status", 1);
        }else
        queryWrapper.like("remark", remark).like("source", source).like("phone", phone).like("anq", anq).like("odd", odd).like("status", 1);
    	
    	
    	
    	int totalHk=0,totalTz=0,total=0;
        Map<String, Object> map = new HashMap<>();
    	List<Bill> Billlist= billService.list(queryWrapper);
    	for (int i = 0; i < Billlist.size(); i++) {
    		if(Billlist.get(i).getSource().equals("货款"))
    			totalHk+=Billlist.get(i).getMoney();
    		
    		if(Billlist.get(i).getSource().equals("投资"))
    			totalTz+=Billlist.get(i).getMoney();
    		total+=Billlist.get(i).getMoney();
			
		}
    	
        map.put("totalHk",totalHk);
        map.put("total",total);
        map.put("totalTz",totalTz);
        return map;
    }
    
    @RequestMapping("/qiankuantotal")
    public Object qiankuantotal(HttpServletRequest request,String name2,String odd,String site,String anq,String time){
    	Map<String, Object> map = new HashMap<>();
    	HttpSession session= request.getSession();
        String username = session.getAttribute("username")+"";
        String quxian = session.getAttribute("quxian")+"";
        String truename = session.getAttribute("truename")+"";
        QueryWrapper<Odd> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("name2", name2).like("odd", odd).like("site", site).like("anq", anq);

        if(time!=null&&!time.equals("")&&time.length()>13&&time.indexOf("-")!=-1){
            String timestart=time.substring(0,10);
            String timeend=time.substring(12);
            queryWrapper.le("time", timeend);
            queryWrapper.ge("time", timestart);
        }
	    	if(quxian.equals("2")){
	    		queryWrapper.eq("saisie", truename);
	    	}
	   List<Odd> oddlist =OddService.list(queryWrapper);
        Double debt=0.00;
    	for (int i = 0; i < oddlist.size(); i++) {
    		debt+=oddlist.get(i).getDebt();
		}
        map.put("debt",debt);
        return map;
    }
    
  //欠款统计
    @RequestMapping("/seleodd欠款")
    public Object seleodd(HttpServletRequest request){
    	String pageNo=request.getParameter("page");
		String pagesize=request.getParameter("limit");
    	Integer i = Integer.parseInt(pageNo); 
    	Integer n = Integer.parseInt(pagesize); 
    	Map<String, Object> map = new HashMap<>();
    	List<Odd> a= OddService.list();

    	if(n!=5000)PageHelper.offsetPage((i-1)*n, n);
        map.put("data",OddService.list());
    	HttpSession session= request.getSession();
        String username = session.getAttribute("username")+"";
        String quxian = session.getAttribute("quxian")+"";
        String truename = session.getAttribute("truename")+"";

    	if(quxian.equals("1")){
    		System.out.println("进入角色："+truename);

        	a= OddService.list(new QueryWrapper<Odd>().eq("saisie", truename));
        	if(n!=5000)PageHelper.offsetPage((i-1)*n, n);
            map.put("data",OddService.list(new QueryWrapper<Odd>().eq("saisie", truename)));
    	}
    	if(quxian.equals("2")){
    		System.out.println("进入角色："+truename);

        	a= OddService.list(new QueryWrapper<Odd>().eq("anq", truename));
        	if(n!=5000)PageHelper.offsetPage((i-1)*n, n);
            map.put("data",OddService.list(new QueryWrapper<Odd>().eq("anq", truename)));
    	}
    	map.put("code",0);
        map.put("count",a.size());
        map.put("msg"," ");
    return map;
    }
}
